package com.test.okhttp.request;


import okhttp3.*;

import java.io.*;
import java.util.*;

/**
 * @author 代廷波
 * @className: CommonRequest
 * @description:
 * @create 2018/11/13 0013-14:37
 **/
public class CommonRequest {

    public static Request createGetRequest(String url, RequestParams params){
        StringBuffer sb = new StringBuffer(url).append("?");

        if (params != null){
            for (Map.Entry<String,String> entry : params.urlParams.entrySet()) {
                sb.append(entry.getKey()).append("=")
                        .append(entry.getValue()).append("&");
            }
            return new Request.Builder().url(sb.substring(0,sb.length()-1)).get().build();

        }

        return null;
    }

    public static Request createPostRequest(String url, RequestParams params){
        FormBody.Builder builder = new FormBody.Builder();
        if (params != null){
            for (Map.Entry<String,String> entry : params.urlParams.entrySet()) {
                builder.add(entry.getKey(),entry.getValue());
            }
            FormBody body =  builder.build();
            return new Request.Builder().url(url).post(body).build();

        }
        return null;
    }

    private static  final MediaType file_type = MediaType.parse("application/octet-stream");

    public static Request createMultipartRequest(String url, RequestParams params){
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(file_type);
        if (params != null){
            for (Map.Entry<String,Object> entry : params.fileParams.entrySet()) {
               if(entry.getValue() instanceof File){
                   builder.addPart(MultipartBody.Part.createFormData(entry.getKey(),
                           null,
                           RequestBody.create(file_type,(File)entry.getValue())));
               }else{
                   builder.addFormDataPart(entry.getKey(),String.valueOf(entry.getValue()));
               }
            }
            return new Request.Builder().url(url).post(builder.build()).build();

        }
        return null;
    }


}
